package com.car.action.admin;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

import com.alibaba.fastjson.JSONObject;
import com.car.common.model.AdminLog;
import com.car.common.model.AdminUser;
import com.car.common.model.Area;
import com.car.common.model.Card;
import com.car.common.model.CardDiscuss;
import com.car.common.model.CardImg;
import com.car.common.model.CardTopic;
import com.car.common.model.MessageUnreadNum;
import com.car.common.model.NavyUsers;
import com.car.common.model.RemindMessage;
import com.car.common.model.Social;
import com.car.common.model.Topics;
import com.car.common.model.UserFriends;
import com.car.common.model.UserHellos;
import com.car.common.model.Users;
import com.car.common.model.UsersInfo;
import com.car.common.model.VipRecord;
import com.car.intercept.AdminInterceptor;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.plugin.ehcache.IDataLoader;
import com.utils.APIJSON;
import com.utils.CookiesUtil;
import com.utils.DateUtil;
import com.utils.PicUtil;
import com.utils.RongCloudUtil;
import com.utils.StringUtil;
import com.utils.SystemClock;

@Before(AdminInterceptor.class)
public class NavyUserController extends Controller {

	public void index() {
        AdminUser adminUser = getSessionAttr(LoginController.ADMIN_SESSION_KEY);
        String sql = " select u.*,FROM_UNIXTIME(u.birthday,'%Y-%m-%d') as birthday_string, ae.name as area_name,iu.im_num,num1.num as num1,num2.num as num2,num3.num as num3, CASE u.sex  WHEN '1' THEN '男' WHEN '2' THEN '女' WHEN '3' THEN 'CD' WHEN '4' THEN 'FtM' WHEN '5' THEN 'MtF'  ELSE '其他' END as sex_name,case u.is_true when '2' then '第三方登录' else '注册用户' end as is_true_name " ;
        sql += ", FROM_UNIXTIME(u.create_time,'%Y-%m-%d %H:%i') as create_time_string , FROM_UNIXTIME(u.vip_end_time,'%Y-%m-%d') as vip_end_time_string ";
        String andSql = " from  users u left join navy_users as a on u.id = a.user_id left join area ae on ae.code = u.area_id left join im_unread iu on iu.user_id = u.id left join message_unread_num num1 on num1.user_id=u.id and num1.type= 1  left join message_unread_num num2 on num2.user_id=u.id and num2.type= 2  left join message_unread_num num3 on num3.user_id=u.id and num3.type= 3 ";
        
        
        andSql += " where a.admin_user_id = " + adminUser.getId() ;
        if (!StringUtil.empty(getPara("user_mobile"))) {
			andSql += " and u.user_mobile ='"+ getPara("user_mobile") +"'";
        }

        andSql += " order by num2 desc  ";
        List<Users> navyUsers = Users.dao.find(sql + andSql);
        
        for(Users users : navyUsers) {
        	if (users.getNickName() != null) {
        		users.setNickName(StringUtil.decode(users.getNickName()));
        	}
        }
        setAttr("list", navyUsers);
        setAttr("user_mobile", getPara("user_mobile"));
        render("index.html");
	}
	
	
	public void new_index() {
		 ArrayList<Area> areaList = CacheKit.get("constant", "arealist", new IDataLoader(){
		       public Object load() {
		           return Area.dao.getIProvince();
		}});
		setAttr("area_list", areaList);
		
        String sql = " select u.*,FROM_UNIXTIME(u.birthday,'%Y-%m-%d') as birthday_string, ae.name as area_name,iu.im_num,num1.num as num1,num2.num as num2,num3.num as num3, CASE u.sex  WHEN '1' THEN '男' WHEN '2' THEN '女' WHEN '3' THEN 'CD' WHEN '4' THEN 'FtM' WHEN '5' THEN 'MtF'  ELSE '其他' END as sex_name  ";
        sql += ", FROM_UNIXTIME(u.create_time,'%Y-%m-%d %H:%i') as create_time_string , FROM_UNIXTIME(u.vip_end_time,'%Y-%m-%d') as vip_end_time_string ";
        String andSql = " from  users u left join navy_users as a on u.id = a.user_id left join area ae on ae.code = u.area_id left join im_unread iu on iu.user_id = u.id left join message_unread_num num1 on num1.user_id=u.id and num1.type= 1  left join message_unread_num num2 on num2.user_id=u.id and num2.type= 2  left join message_unread_num num3 on num3.user_id=u.id and num3.type= 3 ";
        andSql += " where a.admin_user_id > 0  ";
        if(!StringUtil.empty(getPara("zu"))) {
        	andSql += " and u.zu = '" + getPara("zu") + "' ";
        }
        if(!StringUtil.empty(getPara("is_true"))) {
        	andSql += " and u.is_true = " + getPara("is_true") ;
        }
        if(!StringUtil.empty(getPara("auth_badge"))) {
        	andSql += " and u.auth_badge > 0 ";
        } else {
        	andSql += " and u.auth_badge = 0 ";
        }
    	if (!StringUtil.empty(getPara("minage"))) {
			andSql += " and u.birthday < " +(SystemClock.now()/1000L - getParaToInt("minage") * 365 * 24*60* 60);
        }
		if (!StringUtil.empty(getPara("maxage"))) {
			andSql += " and u.birthday > " +(SystemClock.now()/1000L - getParaToInt("maxage") * 365 * 24*60* 60);
        }
		if (!StringUtil.empty(getPara("zu"))) {
			andSql += " and u.zu = '" +getPara("zu")+"' ";
        }
		if (!StringUtil.empty(getPara("tag_ids"))) {
			andSql += " and u.tag_ids like '%" +getPara("tag_ids")+",%' ";
        }
		if (!StringUtil.empty(getPara("sex"))) {
			andSql += " and u.sex = " +getPara("sex");
        }
		if (!StringUtil.empty(getPara("user_mobile"))) {
			andSql += " and u.user_mobile ='"+ getPara("user_mobile") +"'";
        }
        List<Users> navyUsers = Lists.newArrayList();
        String person = getPara("person");
        if(!StringUtil.empty(getPara("area"))) {
	        andSql += " and ae.code = " + getPara("area");
	        andSql += " order by num2 desc limit 1000 ";
	        navyUsers = Users.dao.find(sql + andSql);
        } else {
        	 if(StringUtil.empty(person)) {
            	 person = CookiesUtil.getName(getRequest(), "person");
            } else {
            	if ("100".equals(person)) {
            		CookiesUtil.add(getResponse(), "person", "0");
            	} else {
            		andSql += StringUtil.getSQLForPerson(getPara("person"));
            		andSql += " order by num2 desc limit 1000 ";
            		navyUsers = Users.dao.find(sql + andSql);
            		ArrayList<Area> areaList2 = CacheKit.get("constant", "arealist_"+ person, new IDataLoader(){
      			       public Object load() {
 	     			           return Area.dao.getIProvince(getPara("person"));
 	     			}});
 	     	 		setAttr("area_list", areaList2);
            		CookiesUtil.add(getResponse(), "person", person);
            	}
            	
            }
        }
       
        for(Users users : navyUsers) {
        	if (!StringUtil.empty(users.getNickName())) {
        		users.setNickName(StringUtil.decode(users.getNickName()));
        	}
        }
        
        setAttr("minage",  getPara("minage"));
        setAttr("maxage",  getPara("maxage"));
        setAttr("tag_ids", getPara("tag_ids"));
        setAttr("person", person);
        setAttr("zu", getPara("zu"));
        setAttr("area", getPara("area"));
        setAttr("is_true", getPara("is_true"));
        setAttr("auth_badge", getPara("auth_badge"));
        setAttr("sex", getPara("sex"));
        setAttr("user_mobile", getPara("user_mobile"));
        setAttr("list", navyUsers);
        
        List<AdminUser> adminList = AdminUser.dao.find("select id,user_name from admin_user where id > 1 order by id desc ");
        setAttr("admin_list", adminList);
        render("new_index.html");
	}
	
	
	public void add_card() {
		ArrayList<Social> socialList = CacheKit.get("constant", "sociallist", new IDataLoader(){
		       public Object load() {
		           return Social.dao.getAll();
		}});
 	
	 	ArrayList<Area> areaList = CacheKit.get("constant", "arealist", new IDataLoader(){
			       public Object load() {
			           return Area.dao.getProvince();
		}});
	 	
		ArrayList<Topics> topicList = CacheKit.get("constant", "topicList", new IDataLoader(){
		       public Object load() {
		           return Topics.dao.getAll();
		}});
	 	setAttr("social_list", socialList);
	 	setAttr("area_list", areaList);
	 	setAttr("topic_list", topicList);
	 	Users users = Users.dao.findById(getPara("user_id"));
	 	if (users != null ){
	 		users.setUserHeader(users.getUserHeader() + PicUtil.QINIU_CUT_ADMIN);
	 		users.setNickName(StringUtil.decode(users.getNickName()));
	 	}
	 	//+" and create_time > " + SystemClock.now()/1000L
	 	List<Card> cardList = Card.dao.find("select * , FROM_UNIXTIME(create_time,'%Y-%m-%d %H:%i') as  create_time_string from card where user_id = " + getPara("user_id") );
	 	for(Card card : cardList) {
	 		card.setContent(StringUtil.decode(card.getContent()));
	 	}
	 	setAttr("history", cardList);
	 	setAttr("time", SystemClock.now()/1000L);
	 	setAttr("users", users);
	 	setAttr("user_id", getPara("user_id"));
		render("add_card.html");
	}
	
	public void edit_card() {
		ArrayList<Social> socialList = CacheKit.get("constant", "sociallist", new IDataLoader(){
		       public Object load() {
		           return Social.dao.getAll();
		}});
 	
	 	ArrayList<Area> areaList = CacheKit.get("constant", "arealist", new IDataLoader(){
			       public Object load() {
			           return Area.dao.getProvince();
		}});
	 	
		ArrayList<Topics> topicList = CacheKit.get("constant", "topicList", new IDataLoader(){
		       public Object load() {
		           return Topics.dao.getAll();
		}});
	 	setAttr("social_list", socialList);
	 	setAttr("area_list", areaList);
	 	setAttr("topic_list", topicList);
	 	Card one = Card.dao.findById(getPara("id"));
	 	if (one == null) {
	 		add_card();
	 	} else {
	 		Integer userid =  one.getUserId();
		 	Users users = Users.dao.findById(userid);
		 	if (users != null ){
		 		users.setUserHeader(users.getUserHeader() + PicUtil.QINIU_CUT_ADMIN);
		 		users.setNickName(StringUtil.decode(users.getNickName()));
		 	}
		 	List<Card> cardList = Card.dao.find("select * , FROM_UNIXTIME(create_time,'%Y-%m-%d %H:%i:%S') as  create_time_string from card where user_id = " + userid );
		 	for(Card card : cardList) {
		 		card.setContent(StringUtil.decode(card.getContent()));
		 	}
		 	List<CardImg> imgList = CardImg.dao.find("select * from card_img where card_id = " + getPara("id"));
		 	
		 	one.setContent(StringUtil.decode(one.getContent()));
		 	
		 	List<CardDiscuss> discussList = CardDiscuss.dao.find("select a.id, a.content, FROM_UNIXTIME(a.create_time,'%Y-%m-%d %H:%i') as  create_time_string,u.nick_name,u.user_header from card_discuss as a LEFT JOIN users as u on u.id = a .user_id where a.card_id = " + getPara("id"));
		 	for(CardDiscuss d : discussList) {
		 		d.setContent(StringUtil.decode(d.getContent()));
		 	}
		 	
		 	setAttr("one", one);
		 	setAttr("discuss_list", discussList);
		 	setAttr("create_time_string", DateUtil.commonDateTimeFormat.format(new Date(one.getCreateTime()*1000L)));
		 	
		 	setAttr("time", SystemClock.now()/1000L);
		 	
		 	
		 	setAttr("history", cardList);
		 	setAttr("img_list", imgList);
		 	
		 	setAttr("users", users);
		 	setAttr("user_id", getPara("user_id"));
			render("edit_card.html");
			
			
	 	}
	 	
	}
	
	public void card_save() {
		Card one = new Card();
		int userId = getParaToInt("user_id");
		String images = getPara("images");
		String topics = getPara("topics");
		one.setUserId(userId);
		one.setContent(StringUtil.encode(getPara("content")));
		one.setUserId(userId);
		one.setImages(images);
		one.setImgCheck(1);
		one.setIsShow(1);
		one.setIsCheck(1);
		one.setTagsId(getParaToInt("social"));
		one.setTopicId(topics);
		one.setCreateTime(SystemClock.now()/1000L);
		one.setUpdateTime(SystemClock.now()/1000L);
		one.setTCreateTime(SystemClock.now()/1000L);
		String create_time = getPara("create_time");
		if (!StringUtil.empty(create_time)) {
			try {
				one.setCreateTime(DateUtil.commonDateTimeFormat.parse(create_time).getTime() /1000L);
			} catch (ParseException e) {
			}
		}
		one.setHeat(100 + new Random().nextInt(900));
		one.setViews(50 + new Random().nextInt(100));
		if (one.save()) {
			int card_id = one.getInt("id");
			if (images != null && images.length() > 0) {
				String [] imagesArray = images.split(",");
				for (String image : imagesArray) {
					CardImg img = new CardImg();
					img.setCardId(card_id);
					img.setImageUrl(image);
					img.setImgCheck(1);
					img.setCreateTime(SystemClock.now()/1000L);
					img.setUpdateTime(SystemClock.now()/1000L);
					img.save();
				}
			}
			if (topics != null && topics.length() > 0) {
				String [] topicsArray = topics.split(",");
				for (String t : topicsArray) {
					CardTopic topic = new CardTopic();
					topic.setCardId(card_id);
					topic.setTopicId(Integer.valueOf(t));
					topic.setCreateTime(SystemClock.now()/1000L);
					topic.setUpdateTime(SystemClock.now()/1000L);
					topic.save();
				}
			}
			new CardController().giveABPoint(userId);
			AdminUser adminUser = getSessionAttr(LoginController.ADMIN_SESSION_KEY);
			AdminLog.save(adminUser.getId(), AdminLog.ADMIN_LOG_TYPE_CARD, "增加帖子 " + card_id +" 标题 " + getPara("content"));
		}
		renderText("操作成功!");
		
	}
	
	
	public void card_update() {
		Card one = Card.dao.findById(getPara("id"));
		String topics = getPara("topics");
		one.setContent(StringUtil.encode(getPara("content")));
		one.setTagsId(getParaToInt("social"));
		one.setTopicId(topics);
		one.setUpdateTime(SystemClock.now()/1000L);
		String create_time = getPara("create_time");
		if (!StringUtil.empty(create_time)) {
			try {
				one.setCreateTime(DateUtil.commonDateTimeFormat.parse(create_time).getTime() /1000L);
			} catch (ParseException e) {
			}
		}
		one.update();
		renderText("操作成功!");
	}
	
	public void deleteDiscuss() {
		Db.delete("delete from card_discuss where id = " + getPara("id"));
		renderText("操作成功!");
	}
	
	
	public void discuss() {
		CardDiscuss one = new CardDiscuss();
		one.setContent(StringUtil.encode(getPara("content")));
		one.setCardId(getParaToInt("card_id"));
		Users users = Users.dao.findFirst("select * from users where is_true = 3 and sex = "+getPara("sex") +" ORDER BY RAND() LIMIT 1 ");
		one.setBuserId(users.getId().intValue());
		one.setUserId(users.getId().intValue());
		one.setUpdateTime(SystemClock.now()/1000L);
		String create_time = getPara("create_time");
		if (!StringUtil.empty(create_time)) {
			try {
				one.setCreateTime(DateUtil.commonDateTimeFormat.parse(create_time).getTime() /1000L);
			} catch (ParseException e) {
			}
		}
		one.save();
		
		Db.update("update card set discuss = discuss + 1,discuss_cnt = discuss_cnt + 1,views = views + 50,t_views = t_views + 50 where id = " + getParaToInt("card_id"));
		renderText("操作成功!");
	}
	
	public void discuss_list() {
		
	 	ArrayList<Area> areaList = CacheKit.get("constant", "arealist", new IDataLoader(){
			       public Object load() {
			           return Area.dao.getIProvince();
			}});
	 	setAttr("area_list", areaList);
		/*
		List<RemindMessage> remindMsgList = RemindMessage.dao.find("select a.id,a.user_id,a.type,a.create_time,a.buser_id,a.remind_id,u.nick_name,u.user_header,u.sex,u.user_mobile,CASE u.sex  WHEN '1' THEN '男' WHEN '2' THEN '女' WHEN '3' THEN 'CD' WHEN '4' THEN 'FtM' WHEN '5' THEN 'MtF'  ELSE '其他' END as sex_name,FROM_UNIXTIME(a.create_time,'%Y-%m-%d %H:%i') as create_time_string , FROM_UNIXTIME(u.vip_end_time,'%Y-%m-%d') as vip_end_time_string from remind_message as a left join users u on u.id = a.user_id where a.user_id = "+ getPara("user_id") +" order by a.create_time desc");
    	List<Map<String,Object>> result = Lists.newArrayList();
    	for(RemindMessage one : remindMsgList) {
    		Map<String,Object> map = Maps.newHashMap();
    		map.put("id", one.get("id"));
    		map.put("user_mobile", one.get("user_mobile"));
    		map.put("user_id", one.get("user_id"));
    		map.put("nick_name", StringUtil.decode(one.getStr("nick_name")));
    		map.put("sex_name", one.get("sex_name"));
    		
    		int type = one.getInt("type");
    		if (type == 1) {
    			Card card = Card.dao.findById(one.get("remind_id"));
    			if (card != null) {
    				map.put("content", StringUtil.decode(card.getContent()));
    			}
    		} else {
    			CardDiscuss cardDiscuss = CardDiscuss.dao.findById(one.get("remind_id"));
    			if (cardDiscuss != null) {
    				map.put("content", StringUtil.decode(cardDiscuss.getContent()));
    			}
    		}
    		
    		map.put("create_time_string", one.get("create_time_string"));
    		map.put("vip_end_time_string", one.get("vip_end_time_string"));
    		result.add(map);
    	}
    	setAttr("list", result);
    	*/
		int user_id = getParaToInt("user_id");
		//MessageUnreadNum.dao.clearNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_DISCUSS, user_id);
		setAttr("user_id", user_id);
		// String where =" where (a.create_time > 1529144640 and ( (a.user_id = a.buser_id and  d.user_id = "+user_id+") or (a.buser_id = "+user_id+") and a.user_id <> a.buser_id  ))  or (a.create_time <= 1529144640 and a.buser_id = "+user_id+") order by a.create_time desc ";
		
		String where = " where a.create_time != "+ SystemClock.FUTURE_TIME +" and (a.create_time <= 1529144640 and a.buser_id = " + user_id + ") or ((a.create_time > 1529144640 and ( (a.user_id = a.buser_id and  d.user_id = " + user_id + ") or (a.buser_id = "+ user_id +") and a.user_id <> a.buser_id  ))) order by a.create_time desc";
		List<CardDiscuss> discussList = CardDiscuss.dao.find("select case c.is_true when '2' then '第三方登录' else '注册用户' end as is_true_name,a.id,a.create_time,a.user_id,a.buser_id,a.content,a.card_id,u.nick_name,IFNULL(u.vip_end_time,0) as vip_end_time,IFNULL(u.is_gray,0) as is_gray,u.user_header,u.user_mobile,u.sex,c.nick_name nickname,u.nick_name,u.user_mobile,CASE u.sex  WHEN '1' THEN '男' WHEN '2' THEN '女' WHEN '3' THEN 'CD' WHEN '4' THEN 'FtM' WHEN '5' THEN 'MtF'  ELSE '其他' END as sex_name,FROM_UNIXTIME(a.create_time,'%Y-%m-%d %H:%i') as create_time_string , FROM_UNIXTIME(u.vip_end_time,'%Y-%m-%d') as vip_end_time_string,d.user_id as card_user_id,d.content as card_content from card_discuss as a left join users u on u.id = a.user_id left join card d on d.id = a.card_id left join users c on c.id = a.buser_id " + where);
		
//		List<CardDiscuss> discussList = CardDiscuss.dao.find("a.id,a.create_time,a.user_id,a.buser_id,a.content,a.card_id,b.nick_name,b.vip_end_time,b.user_header,b.user_mobile,b.sex,c.nick_name nickname,d.user_id as card_user_id,d.content as card_content,IFNULL(u.vip_end_time,0) as vip_end_time,IFNULL(u.is_gray,0) as is_gray,CASE u.sex  WHEN '1' THEN '男' WHEN '2' THEN '女' WHEN '3' THEN 'CD' WHEN '4' THEN 'FtM' WHEN '5' THEN 'MtF'  ELSE '其他' END as sex_name,FROM_UNIXTIME(a.create_time,'%Y-%m-%d %H:%i') as create_time_string , FROM_UNIXTIME(u.vip_end_time,'%Y-%m-%d') as vip_end_time_string,d.user_id as card_user_id,d.content as card_content from card_discuss as a left join users u on u.id = a.user_id left join card d on d.id = a.card_id left join users c on c.id = a.buser_id ");
		for(CardDiscuss one : discussList) {
			one.setContent(StringUtil.decode(one.getContent()));
		}
		setAttr("list", discussList);
		
		MessageUnreadNum.dao.clearNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_DISCUSS, user_id);
		
	    setAttr("now", SystemClock.now()/1000);
		render("discuss_list.html");
	}
	
	
	public void giveDiscuss() {
		int card_id = getParaToInt("card_id");
		Card card = Card.dao.findById(card_id);
		if (card != null) {
			CardDiscuss one = new CardDiscuss();
			one.setContent(StringUtil.encode(getPara("content")) );
			one.setCardId(card_id);
			int userid = getParaToInt("user_id");
			one.setUserId(userid);
			one.setBuserId(userid);
			one.setCreateTime(SystemClock.now()/1000L);
        	one.setUpdateTime(SystemClock.now()/1000L);
        	one.set("type", 1);
			if (one.save()) {
				Db.update("update card set discuss = discuss + 1,discuss_cnt = discuss_cnt + 1,views = views + 50,t_views = t_views + 50 where id = " + card_id);
//				MessageUnreadNum.dao.clearNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_DISCUSS, card.getUserId());
				//增加未读消息数
				MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_DISCUSS, card.getUserId());
				
				
			}
			renderText("操作成功!");
		} else {
			renderText("帖子不存在!");	
		}
	}
	
	
	
    public void focus_list() {
    	List<RemindMessage> remindMsgList = RemindMessage.dao.find("select a.id,a.user_id,a.type,a.create_time,a.buser_id,a.remind_id,u.nick_name,u.user_header,u.sex,u.user_mobile,CASE u.sex  WHEN '1' THEN '男' WHEN '2' THEN '女' WHEN '3' THEN 'CD' WHEN '4' THEN 'FtM' WHEN '5' THEN 'MtF'  ELSE '其他' END as sex_name,FROM_UNIXTIME(a.create_time,'%Y-%m-%d %H:%i') as create_time_string , FROM_UNIXTIME(u.vip_end_time,'%Y-%m-%d') as vip_end_time_string from remind_message as a left join users u on u.id = a.user_id where a.user_id = "+ getPara("user_id") +" order by a.create_time desc");
    	List<Map<String,Object>> result = Lists.newArrayList();
    	for(RemindMessage one : remindMsgList) {
    		Map<String,Object> map = Maps.newHashMap();
    		map.put("id", one.get("id"));
    		map.put("user_mobile", one.get("user_mobile"));
    		map.put("user_id", one.get("user_id"));
    		map.put("nick_name", StringUtil.decode(one.getStr("nick_name")));
    		map.put("sex_name", one.get("sex_name"));
    		
    		int type = one.getInt("type");
    		if (type == 1) {
    			Card card = Card.dao.findById(one.get("remind_id"));
    			if (card != null) {
    				map.put("content", StringUtil.decode(card.getContent()));
    			}
    		} else {
    			CardDiscuss cardDiscuss = CardDiscuss.dao.findById(one.get("remind_id"));
    			if (cardDiscuss != null) {
    				map.put("content", StringUtil.decode(cardDiscuss.getContent()));
    			}
    		}
    		
    		map.put("create_time_string", one.get("create_time_string"));
    		map.put("vip_end_time_string", one.get("vip_end_time_string"));
    		result.add(map);
    	}
    	setAttr("list", result);
    	render("focus_list.html");
    }
	
	@Before(AdminInterceptor.class)
	public void answer_card() {
		int user_id = getParaToInt("user_id");
		CardDiscuss discuss = CardDiscuss.dao.findById(getPara("id"));
		CardDiscuss one = new CardDiscuss();
		one.setContent(StringUtil.decode(getPara("content")));
		one.setUserId(user_id);
		one.setBuserId(discuss.getBuserId());
		one.setCardId(discuss.getCardId());
		one.set("discuss_id", getPara("id"));
		one.set("is_discuss", 1);
		one.setType(2);
		one.setCreateTime(SystemClock.now()/1000L);
    	one.setUpdateTime(SystemClock.now()/1000L);
		if (one.save()) {
			Db.update("update card set discuss_cnt = discuss_cnt + 1,discuss = discuss + 1,views = views + 50,t_views = t_views + 50 where id = "+ discuss.getCardId());
//			MessageUnreadNum.dao.removeOne(MessageUnreadNum.MESSAGE_UNREAD_TYPE_DISCUSS, user_id);
			MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_DISCUSS, discuss.getUserId());
		}
		renderText("操作成功!");
	}
	
	@Before(AdminInterceptor.class)
	public void answer() {
		RemindMessage remind = RemindMessage.dao.findById(getPara("id"));
		int type = remind.getType();
		if (type == 1) {
			Card card = Card.dao.findById(remind.getRemindId());
			CardDiscuss one = new CardDiscuss();
			one.setContent(StringUtil.decode(getPara("content")));
			one.setUserId(remind.getUserId());
			one.setBuserId(card.getUserId());
			one.setType(2);
			one.setCreateTime(SystemClock.now()/1000L);
        	one.setUpdateTime(SystemClock.now()/1000L);
        	one.setCardId(card.getId().intValue());
			if (one.save()) {
				Db.update("update card set discuss = discuss + 1,discuss_cnt = discuss_cnt + 1,views = views + 50,t_views = t_views + 50 where id = " + card.getId());
				MessageUnreadNum.dao.removeOne(MessageUnreadNum.MESSAGE_UNREAD_TYPE_DISCUSS, remind.getUserId());
				MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_DISCUSS, card.getUserId());
			}
			
		} else {
			CardDiscuss discuss = CardDiscuss.dao.findById(remind.getRemindId());
			CardDiscuss one = new CardDiscuss();
			one.setContent(StringUtil.decode(getPara("content")));
			one.setUserId(remind.getUserId());
			one.setBuserId(discuss.getUserId());
			one.setCardId(discuss.getCardId());
			one.setType(2);
			one.setCreateTime(SystemClock.now()/1000L);
        	one.setUpdateTime(SystemClock.now()/1000L);
			if (one.save()) {
				Db.update("update card set discuss = discuss + 1,discuss_cnt = discuss_cnt + 1,views = views + 50,t_views = t_views + 50 where id = " + discuss.getCardId());
				MessageUnreadNum.dao.removeOne(MessageUnreadNum.MESSAGE_UNREAD_TYPE_DISCUSS, remind.getUserId());
				MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_DISCUSS, discuss.getUserId());
			}
		}
		renderText("操作成功!");
		// MessageUnreadNum.dao.clearNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_DISCUSS, remind.getUserId());
	}
	

	@Before(AdminInterceptor.class)
	public void friend_app() {
        int page = 1;
        if(!StringUtil.empty(getPara("page"))) {
        	page = getParaToInt("page");
        } 
        String sql = "select h.id,h.user_id, h.target_user_id,h.content, FROM_UNIXTIME(h.create_time,'%Y-%m-%d %H:%i') as create_time_string,hot ";
        String andSql = " from user_hellos as h left join users as u on  h.target_user_id = u.id  left join users as me on  h.user_id = me.id  where h.`status` = 2 and h.delete_time is null and h.today_time > 0 and h.create_time > " + (SystemClock.now()/1000L - 10 *24*3600L) + " ";
        if(!StringUtil.empty(getPara("person"))) {
    		if (!"100".equalsIgnoreCase(getPara("person"))) {
    			andSql += StringUtil.getSQLForPerson4(getPara("person"));
    		}
    	}
        if(!StringUtil.empty(getPara("vip_badpe"))) {
    		andSql += " and me.vip_badpe = " + getPara("vip_badpe");
    	} else {
    		andSql += " and me.vip_badpe = 0 ";
    	} 
        if(!StringUtil.empty(getPara("is_true"))) {
        	andSql += " and u.is_true = " + getPara("is_true");
        }
        andSql += " order by h.id desc ";
        Page<UserHellos> hellos = UserHellos.dao.paginate(page, 20, sql, andSql);
		
		List<Map<String,Object>> result = Lists.newArrayList();
		for(UserHellos one : hellos.getList()) {
			Map<String,Object> temp = Maps.newHashMap();
			temp.put("id", one.get("id"));
			temp.put("hot", one.get("hot"));
			temp.put("user_id", one.get("user_id"));
			temp.put("content", one.get("content"));
			temp.put("target_user_id", one.get("target_user_id"));
			temp.put("create_time_string", one.getStr("create_time_string"));
			// 缓存
			/*
			String cache_key = "friend_app:user_id:"+ one.get("user_id") ;
			Users target_users = CacheKit.get("api", cache_key);
	        if (target_users == null) {
	        	
	        	CacheKit.put("api", cache_key, target_users);
	        }
			*/
			Users target_users = Users.dao.findFirst("select u.is_true, ae.name as name,u.nick_name as nick_name2, CASE u.sex  WHEN '1' THEN '男' WHEN '2' THEN '女' WHEN '3' THEN 'CD' WHEN '4' THEN 'FtM' WHEN '5' THEN 'MtF'  ELSE '其他' END as sex_name from users as u  left join area ae on ae.code = u.area_id where u.id = " + one.get("target_user_id"));
			if (target_users != null && target_users.getIsTrue() > 1) {
				temp.put("target_user_id_area", target_users.getStr("name"));
				temp.put("target_user_id_sex_name", target_users.getStr("sex_name"));
				temp.put("nick_name2", StringUtil.decode(target_users.getStr("nick_name2")));
				// 缓存
				Users users = Users.dao.findFirst("select ae.name as name,u.nick_name,u.vip_badpe, FROM_UNIXTIME(u.birthday,'%Y年%m月%d日') as birthday_string,FROM_UNIXTIME(u.vip_end_time,'%Y-%m-%d') as vip_end_time_string from users as u  left join area ae on ae.code = u.area_id where u.id = " + one.get("user_id"));;
				/*
				String cache_key2 = "friend_app:targer_user_id:"+ one.get("target_user_id") ;
				Users users = CacheKit.get("api", cache_key2);
		        if (users == null) {
		        	users = Users.dao.findFirst("select ae.name as name,u.nick_name,u.vip_badpe, FROM_UNIXTIME(u.birthday,'%Y年%m月%d日') as birthday_string,FROM_UNIXTIME(u.vip_end_time,'%Y-%m-%d') as vip_end_time_string from users as u  left join area ae on ae.code = u.area_id where u.id = " + one.get("user_id"));;
		        	CacheKit.put("api", cache_key2, users);
		        }
		        */
		        
				if(users != null) {
					temp.put("nick_name", StringUtil.decode(users.getStr("nick_name")));
					temp.put("user_id_area", users.getStr("name"));
					temp.put("birthday_string", users.getStr("birthday_string"));
					
					// vip_badpe:1  月  2 季  3 年 4 永    0  没有
					int vip_badpe = users.getInt("vip_badpe");
					String vip_type = "";
					if (vip_badpe == 0) {
						vip_type = "无";
					} else if (vip_badpe == 1) {
						vip_type = "月";
					} else if (vip_badpe == 2) {
						vip_type = "季";
					} else if (vip_badpe == 3) {
						vip_type = "年";
					} else if (vip_badpe == 4) {
						vip_type = "永";
					}
					
					temp.put("vip_type", vip_type);
					temp.put("vip_end_time_string", users.getStr("vip_end_time_string"));
				}
				
				result.add(temp);
			}
		}
		
		String person = getPara("person");
        if(StringUtil.empty(person)) {
        	 person = CookiesUtil.getName(getRequest(), "person");
        } else {
        	if ("100".equals(person)) {
        		CookiesUtil.add(getResponse(), "person", "0");
        	} else {
        		CookiesUtil.add(getResponse(), "person", person);
        	}
        	
        }
        setAttr("vip_badpe", getPara("vip_badpe"));
        setAttr("is_true", getPara("is_true"));
	    setAttr("person", person);
		setAttr("list", result);
		setAttr("page", hellos);
		render("friend_app.html");
	}
	
	
	/**
	 * 查看送了多少热度
	 */
	@Before(AdminInterceptor.class)
	public void friend_app_hot() {
		String result = "没送过热度";
		UserHellos hello = UserHellos.dao.findById(getPara("id"));
		if (hello != null) {
			int user_id = hello.getUserId();
			int target_user_id = hello.getTargetUserId();
			// vip_record
			VipRecord total = VipRecord.dao.findFirst("select sum(hot) as hot from vip_record where user_id = " + user_id + " and target_user_id = " + target_user_id);
			if (total != null ) {
				result = "送" + (total.getBigDecimal("hot") == null ?"0":total.getBigDecimal("hot")) + " 热度";
			} 
			Users users = Users.dao.findById(user_id);
			int times = 5;
			int vip_badpe = users.getInt("vip_badpe");
	        if (vip_badpe == 0){
	        	times = 5;
	        } else if ( vip_badpe == 1){
	        	times = 30;
	        } else if ( vip_badpe == 2){
	            times = 30;
	        } else if (vip_badpe == 3){
	            times = 5000;
	        } else if (vip_badpe == 4){
	            times = 10000;
	        }
	        Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            
	        UserHellos todayTimes = UserHellos.dao.findFirst("select COUNT(id) as cnt from user_hellos where user_id = " + user_id +" and create_time > " + calendar.getTimeInMillis()/1000L);
			result += " 当天剩:" + (times - todayTimes.getInt("cnt")) + "次数";
	        
			UserHellos totalTimes = UserHellos.dao.findFirst("select COUNT(id) as cnt from user_hellos where user_id = " + user_id);
			result += " 总:" + totalTimes.get("cnt");
			UserHellos passTimes = UserHellos.dao.findFirst("select COUNT(id) as cnt from user_hellos where `status` = 1 and user_id = " + user_id);
			result += " 通过:" + passTimes.get("cnt");
			
			UserHellos saynoTimes = UserHellos.dao.findFirst("select COUNT(id) as cnt from user_hellos where `status` = -1 and user_id = " + user_id);
			result += " 拒绝:" + saynoTimes.get("cnt");
			
			result +=  " 距离:" + UsersInfo.dao.get_user_distance(user_id, target_user_id);
		}
		renderText(result);
	}
	
	
	public void friend_pass_one() {
		int id = getParaToInt("hello_id");
		Db.update("update user_hellos set status = " + 1 + " where id = " + id );
		// 同意 -1拒绝 1同意
			// 计算好友数量
		UserHellos oneHello = UserHellos.dao.findById(id);
		int user_id = oneHello.getUserId();
		
		int target_user_id = oneHello.getTargetUserId();
		UserFriends one = UserFriends.dao.findFirst("select id from user_friends where (user_id = "+ user_id +" and target_user_id = " + target_user_id +")  or "+ " (user_id = "+ target_user_id +" and target_user_id = " + user_id +") and status = 1 and delete_time is null order by id desc limit 1 ");
		if (one == null) {
			one = new UserFriends();
			one.setUserId(user_id);
			one.setTargetUserId(target_user_id);
			one.setStatus(1);
			one.setCreateTime(SystemClock.now()/1000L);
			one.setUpdateTime(SystemClock.now()/1000L);
			one.save();
		} else {
			Db.update("update user_friends set status = " + 1 +" where id = " + one.getId());
		}
		// 推送 
		Map<String, String> params = Maps.newHashMap();
		params.put("userId",   		String.valueOf(user_id));
		params.put("blackUserId",   String.valueOf(target_user_id));
		RongCloudUtil.post("http://api-cn.ronghub.com/user/blacklist/remove.json", params);
		
		params.put("userId",   		String.valueOf(target_user_id));
		params.put("blackUserId",   String.valueOf(user_id));
		RongCloudUtil.post("http://api-cn.ronghub.com/user/blacklist/remove.json", params);
		// /user/blacklist/remove.json
		
		MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_FRIEND, target_user_id);
		RongCloudUtil.sendTxt(String.valueOf(user_id), String.valueOf(target_user_id), "我们已经是好友了,一起来聊天吧");
		RongCloudUtil.sendTxt(String.valueOf(target_user_id), String.valueOf(user_id), "我们已经是好友了,一起来聊天吧");
		
		Db.update("update user_hellos set today_time = " + 0 + " where user_id = " + user_id );
		renderText("操作成功!");
	}
	
	@Before(AdminInterceptor.class)
	public void friend_status_select() {
		int status = getParaToInt("status");
		String[] ids = getPara("ids").split(",");
 		for(String id :ids) {
 			if (status == 0) {
 				Db.update("update user_hellos set today_time = " + 0 + " where id = " + id );
 			} else {
 				Db.update("update user_hellos set status = " + status + " where id = " + id );
 	 			// 同意 -1拒绝 1同意
 	 			if (status == 1) {
 	 				// 计算好友数量
 	 				UserHellos oneHello = UserHellos.dao.findById(id);
 	 				int user_id = oneHello.getUserId();
 	 				
 	 				int target_user_id = oneHello.getTargetUserId();
 	 				UserFriends one = UserFriends.dao.findFirst("select id from user_friends where (user_id = "+ user_id +" and target_user_id = " + target_user_id +")  or "+ " (user_id = "+ target_user_id +" and target_user_id = " + user_id +") and status = 1 and delete_time is null order by id desc limit 1 ");
 	 				if (one == null) {
 	 					one = new UserFriends();
 	 					one.setUserId(user_id);
 	 					one.setTargetUserId(target_user_id);
 	 					one.setStatus(1);
 	 					one.setCreateTime(SystemClock.now()/1000L);
 	 					one.setUpdateTime(SystemClock.now()/1000L);
 	 					one.save();
 	 				} else {
 	 					Db.update("update user_friends set status = " + 1 +" where id = " + one.getId());
 	 				}
 	 				// 发送消息
 	 				RongCloudUtil.sendTxt(String.valueOf(user_id), String.valueOf(target_user_id), "我们已经是好友了,一起来聊天吧");
 	 				RongCloudUtil.sendTxt(String.valueOf(target_user_id), String.valueOf(user_id), "我们已经是好友了,一起来聊天吧");
 	 				// 推送 
 	 				Map<String, String> params = Maps.newHashMap();
 	 				params.put("userId",   		String.valueOf(user_id));
 	 				params.put("blackUserId",   String.valueOf(target_user_id));
 	 				RongCloudUtil.post("http://api-cn.ronghub.com/user/blacklist/remove.json", params);
 	 				
 	 				params.put("userId",   		String.valueOf(target_user_id));
 	 				params.put("blackUserId",   String.valueOf(user_id));
 	 				RongCloudUtil.post("http://api-cn.ronghub.com/user/blacklist/remove.json", params);
 	 				// /user/blacklist/remove.json
 	 			} else if (status == -1) {
 	 				UserHellos hello = UserHellos.dao.findById(id);
 	 				if (hello.getHot() > 0 ) {
 	 					int user_id = hello.getUserId();
 	 					Db.update("update users set hot_val = hot_val + " + hello.getHot() + " where id = " + user_id );
 	 				}
 	 				
 	 			}
 			}
 		}
 		renderText("操作成功!");
 		
 	}
	
	
	public  void create() {
		long user_mobile = getParaToLong("mobile");
		int admin_user_id = getParaToInt("admin_user_id");
		for (int i = 0 ;i < 50; i ++) {
			long user_mobile2 = user_mobile + i;
			Users users = Users.dao.findFirst("select id from users where user_mobile ='"+ user_mobile2+"'");
			if (users == null) {
				users = new Users();
				users.setUserMobile(String.valueOf(user_mobile2));
				users.setUserPassword(Users.password("花花爱我"));
				users.setSex(2);
				// 模板1
				int tempid = 1 + new Random().nextInt(10);
				if (tempid ==1) {
					users.setTagIds("16,43,45,67,68,62,47,29,39,66");
					users.setBirthday(835408408L);
				} else if (tempid == 2) {
					users.setTagIds("16,45,67,68,62,29,38,26,10,56");
					users.setBirthday(935286808L);
				} else if (tempid == 3) {
					users.setTagIds("16,43,67,68,62,39,49,66");
					users.setBirthday(933818008L);
				} else if (tempid == 4) {
					users.setTagIds("16,43,67,62,29,39,50");
					users.setBirthday(812858008L);
				} else if (tempid == 5) {
					users.setTagIds("16,43,45,67,68,62,47,35,39");
					users.setBirthday(853466008L);
				} else if (tempid == 6) {
					users.setTagIds("16,43,,67,68,47,39,26");
					users.setBirthday(880250008L);
				} else if (tempid == 7) {
					users.setTagIds("16,43,45,67,39,49,38,66");
					users.setBirthday(821670808L);
				} else if (tempid == 8) {
					users.setTagIds("16,45,67,68,47,39,56");
					users.setBirthday(905478808L);
				} else if (tempid == 9) {
					users.setTagIds("16,43,45,67,68");
					users.setBirthday(935459608L);
				} else if (tempid == 10) {
					users.setTagIds("16,43,45,35,39,50");
					users.setBirthday(875584408L);
				}
				users.setCreateTime(SystemClock.now()/1000L);
				users.setUpdateTime(SystemClock.now()/1000L);
				users.setIsTrue(2);
				users.save();
				
				Long user_id = users.getId();
				
				NavyUsers nusers = new NavyUsers();
				nusers.setUserId(user_id.intValue());
				nusers.setAdminUserId(admin_user_id);
				nusers.save();
				UsersInfo info = new UsersInfo();
				info.setUserId(user_id.intValue());
				if (tempid ==1) {
					info.setHeight(166);
					info.setWeight(47);
					// 情感状态
					info.setOrientation(1);
					info.setEmotion(2);
				} else if (tempid == 2) {
					info.setHeight(164);
					info.setWeight(45);
					// 情感状态
					info.setOrientation(1);
					info.setEmotion(2);
				} else if (tempid == 3) {
					info.setHeight(171);
					info.setWeight(50);
					// 情感状态
					info.setOrientation(1);
					info.setEmotion(2);
				} else if (tempid == 4) {
					info.setHeight(168);
					info.setWeight(49);
					// 情感状态
					info.setOrientation(1);
					info.setEmotion(2);
				} else if (tempid == 5) {
					info.setHeight(163);
					info.setWeight(43);
					// 情感状态
					info.setOrientation(1);
					info.setEmotion(2);
				} else if (tempid == 6) {
					info.setHeight(165);
					info.setWeight(45);
					// 情感状态
					info.setOrientation(1);
					info.setEmotion(2);
				} else if (tempid == 7) {
					info.setHeight(156);
					info.setWeight(47);
					// 情感状态
					info.setOrientation(1);
					info.setEmotion(2);
				} else if (tempid == 8) {
					info.setHeight(153);
					info.setWeight(43);
					// 情感状态
					info.setOrientation(1);
					info.setEmotion(2);
				} else if (tempid == 9) {
					info.setHeight(171);
					info.setWeight(53);
					// 情感状态
					info.setOrientation(3);
					info.setEmotion(2);
				} else if (tempid == 10) {
					info.setHeight(166);
					info.setWeight(48);
					// 情感状态
					info.setOrientation(3);
					info.setEmotion(2);
				} 
				info.save();
			}
			
		}
		renderText("OK");
	}
}
